package jeecg.hh.mvc.util;

import java.io.File;
import java.io.FileFilter;
import java.lang.reflect.Method;
import java.util.LinkedHashSet;
import java.util.Set;

import jeecg.hh.mvc.annotation.RequstMapping;


public class FindRequestMappingMethod {
	
	private static Set<Class<?>> clazzSet=new LinkedHashSet<Class<?>>();
	
	public static Class<?> getClassByRequestMapping(String requestMappingPath){
		Class<?> targetClass=null;
		for (Class<?> clazz : clazzSet) {
			Method[] method=clazz.getMethods();
			for (Method method2 : method) {
				if(method2.isAnnotationPresent(RequstMapping.class)){
					try {
						if(RequstMapping.class.newInstance().value().equals(requestMappingPath)){
							targetClass=clazz;
						}
					} catch (InstantiationException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IllegalAccessException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					break;
				}
			}
			if(targetClass!=null){
				break;
			}
		}
		return targetClass;
	}
	
	public static void findAndAddClassInPackageByFile(
			String packageName,
			String packagePath,
			final boolean recursive,
			Set<Class<?>> clazz)
	{
		File dir=new File(packagePath);
		if(!dir.exists()||!dir.isDirectory()){
			return;
		}
		
		File[] dirFiles=dir.listFiles(new FileFilter() {
			//自定义过滤规则，如果可以循环
			@Override
			public boolean accept(File file) {
				// TODO Auto-generated method stub
				return (file.isDirectory()&&file.getName().endsWith("control"));
			}
		});
		//循环所有文件。
		for(File file:dirFiles){
			if(file.isDirectory()){
				findAndAddClassInPackageByFile(packageName+"."+file.getName(), file.getAbsolutePath(), recursive, clazz);
			}else{
				try {
				String className=file.getName().substring(0,file.getName().length()-6);
					clazz.add(Thread.currentThread().getContextClassLoader().loadClass(packageName+","+className));
				} catch (ClassNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}
